package com.fbli.Thread.ticket;

public class SellTicket {
    public static void main(String[] args) {
        /*SellTicket01 sellTicket01 = new SellTicket01();
        SellTicket01 sellTicket02 = new SellTicket01();
        SellTicket01 sellTicket03 = new SellTicket01();
        sellTicket01.start();
        sellTicket02.start();
        sellTicket03.start();*/
        //会出现超卖问题
        SellTicket02 sellTicket02 = new SellTicket02();
        new Thread(sellTicket02).start();
        new Thread(sellTicket02).start();
        new Thread(sellTicket02).start();
        //依旧有超卖问题
    }
}

//Thread方式
class SellTicket01 extends Thread {
    private static int ticketNum = 100;//让多个线程共享ticketNum

    @Override
    public void run() {
        while (true) {
            if (ticketNum <= 0) {
                System.out.println("售票结束");
                break;
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("窗口" + Thread.currentThread().getName() + "售出一张票" + "剩余票数" + (--ticketNum));
        }
    }
}

//实现接口方式
class SellTicket02 implements Runnable {
    private static int ticketNum = 100;//让多个线程共享ticketNum
    private boolean loop = true;

    public void setLoop(boolean loop) {
        this.loop = loop;
    }

    @Override
    public void run() {
        while (loop){
            sell();
        }
    }
    //要求多个线程的锁对象为同一个
    //    同步方法（静态的） 的锁在当前类本身
    //    public synchronized static void m1(){} 锁是在SellTicket.class上
    public synchronized static void m1(){}
    public static void m2(){
        synchronized (SellTicket.class){
            System.out.println("m2");
        }
    }
    //synchronized加锁，实现线程同步
    //private synchronized void sell() {}就是一个同步方法
    //这时锁在this对象上
    //也可以在代码块上写synchronized，同步代码块，互斥锁还是在this对象上
    private void sell() {
        synchronized (this) {
            if (ticketNum<=0){
                System.out.println("售票结束");
                loop = false;
                return;
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("窗口" + Thread.currentThread().getName() + "售出一张票" + "剩余票数" + (--ticketNum));
        }
    }
}